package top.callname.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import top.callname.util.ConnDB;

import java.sql.Connection;
import java.sql.ResultSet;

public class BaseDao {

		public Connection conn= null;
		public PreparedStatement pstm = null;
		public ResultSet res,res2 = null;
		
		
		public  ResultSet query(String sql) {
			conn = ConnDB.getConn();
			try {
				pstm = conn.prepareStatement(sql);
				res = pstm.executeQuery();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return res;
		}	
		
		public  boolean adu(String sql) {
				int m=0;
				conn = ConnDB.getConn();
				try {
					pstm = conn.prepareStatement(sql);
					m = pstm.executeUpdate();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				this.closeDB();
				if(m>0) 
					return true;
				else
					return false;
		}  
		
		/**
		 * 
		 * Description:插入成功返回主键 否则返回-1
		 * @param sql
		 * @return
		 */
		public int aduReturnKey(String sql){
			int m=0;
			int resKey=-1;
			conn = ConnDB.getConn();
			try {
				pstm = conn.prepareStatement(sql);
				m = pstm.executeUpdate();
			if(m>0) {
				String sql1 = "SELECT LAST_INSERT_ID()"; 
				pstm = conn.prepareStatement(sql1);
				res = pstm.executeQuery();
					if(res.next()){
						resKey=res.getInt(1);
						this.closeDB();
						return resKey;
					}
				}else{
					this.closeDB();
					return -1;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				this.closeDB();
			}
			return resKey;
		}
		
		public int getCount (String tableName){
			String sql = "select count(1)  from "+tableName;
			Integer count = 0;
			this.query(sql);
			try {
				if(res.next()){
					count = res.getInt(1);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			this.closeDB();
			return count;
		}

		public int getCount (String tableName,String where){
			String sql = "select count(1)  from "+tableName +" "+where;
			Integer count = 0;
			this.query(sql);
			try {
				if(res.next()){
					count = res.getInt(1);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			this.closeDB();
			return count;
		}
		

		/**
		 * 自定义sql查询
		 * @param sql
		 * @return
		 */
		public int getCountBySql (String sql){
			Integer count = 0;
			this.query(sql);
			try {
				if(res.next()){
					count = res.getInt(1);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			this.closeDB();
			return count;
		}
		
		public void closeDB(){
			try {
				if(!this.conn.isClosed()&&this.conn!=null) 
					this.conn.close();
			} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		
	}

